<?php
class TypeAction extends CommonAction {

    public function index()
    {
        $type = M('Type');
        parent::page($type->count());
        $data = $type->order('add_time desc')
                     ->limit($this->limit)
                     ->select();

        $this->assign('data', $data);
        $this->display();
    }

    public function add()
    {
        $type = M('Type');
        if(isset($_POST['send']))
        {
            $this->validate(self::$ADD_SEC);
            $data['type_name'] = $this->_post('type_name');
            $data['add_user'] = session('admin');
            $data['add_time'] = getDateTime();
            if($type->add($data))
            {
                $content = "用户：".session('admin')." 添加了一个供货种类：$data[type_name]";
                addAdminRecord($content);
                redirectByModal('添加种类成功!', self::$SUCCESS, __URL__ . '/index');
            }
        }
        $this->display();
    }

    public function update($id)
    {
        $type = M('Type');
        $currentData = $type->field(array('id', 'type_name'))->where('id='.$id)->find();

        if(isset($_POST['send']))
        {
            $this->validate(self::$UPDATE_SEC);
            $data['type_name'] = $this->_post('type_name');
            $data['id'] = $this->_post('id');
            $type->save($data);
            $content = "用户：".session('admin')." 修改了一个供货种类：$currentData[type_name] 为 $data[type_name]";
            addAdminRecord($content);
            redirectByModal('修改种类成功!', self::$SUCCESS, __URL__.'/index');
        }
        $this->assign('data', $currentData);
        $this->display();
    }

    public function delete()
    {
        $id = $this->_post('id');
        $type = M('Type');
        $data = $type->field('type_name')->where('id='.$id)->find();
        if($type->where('id='.$id)->delete())
        {
            $content = "用户：".session('admin')." 删除了一个供货种类：$data[type_name]";
            addAdminRecord($content);
            redirectByModal('删除种类成功!', self::$SUCCESS, __URL__ . '/index');
        }
    }

    // 验证
    private function validate($sec)
    {
        $type_name = $this->_post('type_name');
        if($type_name == '')
            redirectByModal('种类名称必须填写!', self::$ERROR);
        else if(mb_strlen($type_name, 'utf-8') > 30)
            redirectByModal('种类名称不能超过30位!', self::$ERROR);
        else if($sec == 'add')
        {
            $type = M('Type');
            if($type->where("type_name=$type_name")->find())
                redirectByModal('种类名称已经存在!', self::$ERROR);
        }
    }
}